package com.controller;

import com.bean.Comment;
import com.bean.Post;
import com.bean.User;
import com.db.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentRepository commentRepository;

    @RequestMapping(value="/{postID}" , method = GET)
    public String showUserComment(Model model){
        return "userComment";
    }

    @RequestMapping(value="/{postID}" , method = RequestMethod.POST)
    public String saveComment(HttpServletRequest request, CommentForm commentForm , @PathVariable("postID") int postID, Model model, HttpSession session)
            throws Exception {

        User user = (User) session.getAttribute("user");

        int level = commentRepository.findByPost(new Post(postID)).size() + 1 ;

        String content = new String(commentForm.getContent().getBytes("ISO-8859-1"),"utf-8");

        if(user != null){
            Comment post = new Comment(level,new Post(postID),user,content, new Date());
            commentRepository.save(post);
            session.removeAttribute("postID");

            //postRepository
            //        .save(new Post(postForm.getTopic(), postForm.getContent(), (User) session.getAttribute("user"), new Date(),0,null,1));
            return "redirect:/post/"+postID;
        }
        else
            return "redirect:/";
    }
}
